package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前请求是否是handler() 【所有有@XxxMapping注解的方法  处理器】
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取请求头的token
        String token = request.getHeader("authorization");
        //token为空，响应401  解析token  失败 响应401
        if(ObjectUtil.isEmpty(token) || tokenService.parseToken(token)==null){
            throw new BaseException("认证失败");
        }

        //获取用户id    userid
        Claims claims = tokenService.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        //userid==null  响应401
        if(ObjectUtil.isEmpty(userId)){
            throw new BaseException("认证失败");
        }

        //把userId 存入到ThreadLocal(userThreadLocal)
        UserThreadLocal.set(userId);
        return true;
    }
}
